package com.tianyuan.dplrf.ui.activity;

import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.widget.NestedScrollView;
import androidx.viewpager2.widget.ViewPager2;

import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OnKeyboardListener;
import com.hjq.base.BaseDialog;
import com.hjq.base.action.AnimAction;
import com.hjq.widget.view.ClearEditText;
import com.hjq.widget.view.CountdownView;
import com.hjq.widget.view.RegexEditText;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.tianyuan.dplrf.R;
import com.tianyuan.dplrf.aop.SingleClick;
import com.tianyuan.dplrf.app.AppActivity;
import com.tianyuan.dplrf.ui.adapter.HomePageAdapter;
import com.tianyuan.dplrf.ui.dialog.TipsDialog;
import com.tianyuan.dplrf.ui.dialog.WaitDialog;
import com.tianyuan.dplrf.ui.tim.TIMAppService;
import com.tianyuan.dplrf.ui.tim.bean.UserInfo;
import com.tianyuan.dplrf.ui.tim.config.AppConfig;
import com.tianyuan.dplrf.ui.tim.signature.GenerateTestUserSig;
import com.tianyuan.dplrf.ui.tim.utils.DemoLog;
import com.tianyuan.dplrf.ui.tim.utils.TUIUtils;
import com.tianyuan.dplrf.ui.utiils.Uiutils;

import me.relex.circleindicator.CircleIndicator3;

public class HomePageAct extends AppActivity implements View.OnClickListener {


    private ViewPager2 home_view_banner;
    private CircleIndicator3 cv_guide_indicator;

    private HomePageAdapter mAdapter;
    private ClearEditText edit_phonenum;
    private RegexEditText edit_numcode;
    private CountdownView cv_find_countdown;
    private AppCompatCheckBox user_check;
    private TableRow tab_user_cir;
    private FrameLayout linearcontent;

    private ImageView img_closedia;
    private AppCompatButton btn_guide_complete;
    private TextView btn_home_myhome;
    private TableRow tab_mync;
    private TextView btn_home_onlinemoll;
    private TableRow tab_home_onlinemoll;
    private TextView btn_home_friend;
    private TableRow tab_home_friend;
    private TextView btn_home_gamer;
    private TableRow tab_home_gamer;
    private NestedScrollView nestscroll;
    private AppCompatButton btn_login_dia;
    private boolean isLogin = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_page;
    }

    @Override
    protected void initView() {


        home_view_banner = findViewById(R.id.home_view_banner);
        cv_guide_indicator = findViewById(R.id.cv_guide_indicator);
        edit_phonenum = findViewById(R.id.edit_phonenum);
        edit_numcode = findViewById(R.id.edit_numcode);
        cv_find_countdown = findViewById(R.id.cv_find_countdown);
        user_check = findViewById(R.id.user_check);
        tab_user_cir = findViewById(R.id.tab_user_cir);
        linearcontent = findViewById(R.id.linearcontent);
        cv_find_countdown.setOnClickListener(this);

        img_closedia = findViewById(R.id.img_closedia);
        img_closedia.setOnClickListener(this);

        btn_guide_complete = findViewById(R.id.btn_guide_complete);
        btn_home_myhome = findViewById(R.id.btn_home_myhome);
        tab_mync = findViewById(R.id.tab_mync);
        btn_home_onlinemoll = findViewById(R.id.btn_home_onlinemoll);
        tab_home_onlinemoll = findViewById(R.id.tab_home_onlinemoll);
        btn_home_friend = findViewById(R.id.btn_home_friend);
        tab_home_friend = findViewById(R.id.tab_home_friend);
        btn_home_gamer = findViewById(R.id.btn_home_gamer);
        tab_home_gamer = findViewById(R.id.tab_home_gamer);
        nestscroll = findViewById(R.id.nestscroll);
        btn_login_dia = findViewById(R.id.btn_login_dia);
        tab_mync.setOnClickListener(this);
        tab_home_onlinemoll.setOnClickListener(this);
        tab_home_friend.setOnClickListener(this);
        tab_home_gamer.setOnClickListener(this);
        btn_login_dia.setOnClickListener(this);


        linearcontent.setVisibility(View.GONE);

    }

    @Override
    protected void initData() {
        mAdapter = new HomePageAdapter(this);
        home_view_banner.setAdapter(mAdapter);
        home_view_banner.registerOnPageChangeCallback(mcallback);
        cv_guide_indicator.setViewPager(home_view_banner);

        boolean autoRotateOn = (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1);

        if (UserInfo.getInstance().isAutoLogin()) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    login();
                }
            }, 200);
        }
        Log.e("aata", "initData: " + autoRotateOn);
    }

    private void login(String userId) {
        UserInfo userInfo = UserInfo.getInstance();
        Log.e(getTag(), "login: " + (userInfo == null));
        TIMAppService.getInstance().initBeforeLogin(0);
        UserInfo.getInstance().setUserId(userId);
        String userSig = GenerateTestUserSig.genTestUserSig(userId);
        UserInfo.getInstance().setUserSig(userSig);
        TUILogin.login(getApplicationContext(), GenerateTestUserSig.SDKAPPID, userId, userSig, TUIUtils.getLoginConfig(), new TUICallback() {
            @Override
            public void onError(final int code, final String desc) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc);
//                            mLoginView.setEnabled(true);
                    }
                });
                Log.e(getTag(), "onError: " + code + desc);
            }

            @Override
            public void onSuccess() {
                UserInfo.getInstance().setAutoLogin(true);
                UserInfo.getInstance().setDebugLogin(true);
//                    if (AppConfig.DEMO_UI_STYLE == 0) {
//                        intent = new Intent(LoginForDevActivity.this, MainActivity.class);
//                    } else {
//                        intent = new Intent(LoginForDevActivity.this, MainMinimalistActivity.class);
//                    }
                startActivity(MyFriendActivity.class);
                Log.e(getTag(), "success: ");
                DemoLog.i(getTag(), "MyFriendActivity success = ");
                TIMAppService.getInstance().registerPushManually();
            }
        });
//        if (userInfo == null || userInfo.getUserId() == null || userInfo.getUserId().equals("")){
        //用户id不存在

//        }
    }

    private void login() {
        UserInfo userInfo = UserInfo.getInstance();
        Log.e(getTag(), "login:login " + (userInfo == null));
        TUILogin.login(getApplicationContext(), GenerateTestUserSig.SDKAPPID, userInfo.getUserId(), userInfo.getUserSig(), TUIUtils.getLoginConfig(), new TUICallback() {
            @Override
            public void onError(final int code, final String desc) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc);
//                        startLogin();
                    }
                });
                Log.e(getTag(), "login:lo22gin " + code + ", errorInfo = " + desc);
            }

            @Override
            public void onSuccess() {
//                startMain();
                isLogin = true;
                Log.e(getTag(), "login:lo33gin " + (userInfo == null));
                TIMAppService.getInstance().registerPushManually();
            }
        });
    }

    private final ViewPager2.OnPageChangeCallback mcallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            super.onPageScrollStateChanged(state);
        }

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
        }
    };

    @NonNull
    @Override
    protected ImmersionBar createStatusBarConfig() {
        return super.createStatusBarConfig();
        //设置状态栏字体颜色白色
//                .statusBarDarkFont(false)
        // 隐藏状态栏和导航栏
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        home_view_banner.unregisterOnPageChangeCallback(mcallback);
    }

    private BaseDialog mWaitDialog;
    private int currentLogin = 0;

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.cv_find_countdown:
                //todo 发生验证码
                toast(R.string.common_code_send_hint);
                cv_find_countdown.start();
                break;

            case R.id.tab_home_gamer:
                startActivity(NczdAct.class);
                break;
            case R.id.tab_home_onlinemoll:

                break;
            case R.id.tab_mync:
                currentLogin = 2;
                showLogindia();
//                startActivity(NczdAct.class);

                break;
            case R.id.tab_home_friend:
                currentLogin = 1;
                if (isLogin) {
                    startActivity(MyFriendActivity.class);
                    return;
                }
                showLogindia();


                break;
//            case R.id.btn_home_login:
//                currentLogin = 0;
//                linearcontent.setVisibility(View.VISIBLE);
//                break;
            case R.id.btn_login_dia:
                if (currentLogin == 1) {

                    if (edit_phonenum.getText().length() < 11) {
                        toast("请输入正确的手机号码");
                        return;
                    } else if (!user_check.isChecked()) {
                        toast("请阅读用户协议");
                        return;
                    }
                }

                if (currentLogin == 1) {
                    if (isLogin){
                        startActivity(MyFriendActivity.class);
                        return;
                    }
                    login(edit_phonenum.getText().toString());
                    return;
                }

//                if (edit_phonenum.getText().length() < 11) {
//                    toast("请输入正确的手机号码");
//                    return;
//                } else if (edit_numcode.getText().length() < 6) {
//                    toast("验证码输入错误");
//                    return;
//                } else if (!user_check.isChecked()) {
//                    toast("请阅读用户协议");
//                    return;
//                }

                //验证码验证
                // TODO: 2023/11/15
                //登录成功
//                new TipsDialog.Builder(this)
//                        .setIcon(TipsDialog.ICON_FINISH)
//                        .setMessage("完成")
//                        .show();
                if (mWaitDialog == null) {
                    mWaitDialog = new WaitDialog.Builder(this)
                            // 消息文本可以不用填写
                            .setMessage(getString(R.string.common_loading))
                            .create();
                }
                if (!mWaitDialog.isShowing()) {
                    mWaitDialog.show();
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (currentLogin == 2) {
                                //我的农场
                                startActivity(MinencAct.class);
                            } else if (currentLogin == 1) {
                                startActivity(MyFriendActivity.class);
                            } else {
                                startActivity(NczdAct.class);
                            }

                            hideLogindia();
                            mWaitDialog.dismiss();
                        }
                    }, 2000);
//                    postDelayed(mWaitDialog::dismiss, 2000);
                }

//                startActivity(NczdAct.class);

                break;
            case R.id.img_closedia:
                hideLogindia();
                break;

        }
    }

    private void showLogindia() {
        linearcontent.setVisibility(View.VISIBLE);
        Uiutils.showRightInAnim(linearcontent, getApplicationContext());
    }

    private void hideLogindia() {
        linearcontent.setVisibility(View.GONE);
        Uiutils.showRightOutAnim(linearcontent, getApplicationContext());
    }

}